package db

import (
	gormMysql "gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

type mysql struct {
	username string
	password string
	host     string
	port     string
	db       string
	config   string
	prefix   string
}

func mysqlCreate() *mysql {
	return &mysql{
		config: "charset=utf8mb4&parseTime=True&loc=Local",
	}
}

func (m *mysql) connect() *gorm.DB {
	db, err := gorm.Open(gormMysql.New(gormMysql.Config{
		DSN: m.dns(),
	}), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   m.prefix,
			SingularTable: true,
		},
	})

	if err != nil {
		panic(err)
	}

	return db
}

func (m *mysql) dns() string {
	return m.username + ":" + m.password + "@tcp(" + m.host + ":" + m.port + ")/" + m.db + "?" + m.config
}

func (m *mysql) setUserName(name string) {
	m.username = name
}

func (m *mysql) setPassword(password string) {
	m.password = password
}

func (m *mysql) setName(name string) {
	m.db = name
}

func (m *mysql) setPort(port string) {
	m.port = port
}

func (m *mysql) setHost(host string) {
	m.host = host
}

func (m *mysql) setPrefix(prefix string) {
	m.prefix = prefix
}
